package cjq.demo.thread.ch4_4;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2016/4/27.
 */
public class Main {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

        List<Future<Integer>> resultList = new ArrayList<>();

        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            Integer number = random.nextInt(10);
            FactoriaCalculator calculator = new FactoriaCalculator(number);

            Future<Integer> result = executor.submit(calculator);

            resultList.add(result);
        }

        do{
            System.out.println("Main: Number of Completed Tasks:"+executor.getCompletedTaskCount());
            for (int i = 0; i < resultList.size(); i++) {
                Future<Integer> result = resultList.get(i);
                System.out.println("Main: Task "+i+" "+result.isDone());
            }

            try{
                TimeUnit.MILLISECONDS.sleep(50);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }while(executor.getCompletedTaskCount()<resultList.size());


        System.out.println("Main: Results");
        for (int i = 0; i < resultList.size(); i++) {
            Future<Integer> result = resultList.get(i);
            Integer number = null;
            try{
                number = result.get();
            }catch(InterruptedException e){
                e.printStackTrace();
            }catch(ExecutionException e){
                e.printStackTrace();
            }
            System.out.println("Main: Task "+i+" "+number);
        }

        executor.shutdown();
    }
}
